// MCP 客户端示例 - 演示如何通过 HTTP 调用浏览器操作
import fetch from 'node-fetch';

const BASE_URL = 'http://localhost:3333';

class PlaywrightMCPClient {
  async open(url: string) {
    const response = await fetch(`${BASE_URL}/open`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ url })
    });
    return response.json();
  }

  async click(selector: string) {
    const response = await fetch(`${BASE_URL}/click`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ selector })
    });
    return response.json();
  }

  async fill(selector: string, value: string) {
    const response = await fetch(`${BASE_URL}/fill`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ selector, value })
    });
    return response.json();
  }

  async upload(selector: string, files: string[]) {
    const response = await fetch(`${BASE_URL}/upload`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ selector, files })
    });
    return response.json();
  }

  async wait(selector: string, state: 'attached' | 'visible' | 'hidden' | 'detached' = 'visible') {
    const response = await fetch(`${BASE_URL}/wait`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ selector, state })
    });
    return response.json();
  }

  async screenshot() {
    const response = await fetch(`${BASE_URL}/screenshot`, { method: 'POST' });
    return response.buffer();
  }

  async health() {
    const response = await fetch(`${BASE_URL}/health`);
    return response.json();
  }
}

// 使用示例
async function example() {
  const client = new PlaywrightMCPClient();
  
  try {
    // 检查服务器状态
    console.log('Health check:', await client.health());
    
    // 打开小红书
    console.log('Opening XHS:', await client.open('https://www.xiaohongshu.com/explore'));
    
    // 等待页面加载
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 截图
    const screenshot = await client.screenshot();
    console.log('Screenshot taken, size:', screenshot.length, 'bytes');
    
  } catch (error) {
    console.error('Error:', error);
  }
}

// 如果直接运行此文件，执行示例
if (import.meta.url === `file://${process.argv[1]}`) {
  example();
}

export { PlaywrightMCPClient };
